import { ImageViewer, Swiper, Toast } from 'antd-mobile'
import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import http from '../../api'
import Loading from '../../components/publicComponents/Loading'
import { DetailGoodsDataType, DetailStoreType, GoodsImgs, GoodsTags } from '../../myTypes'
import style from './index.module.css'

interface StoreData {
  area: string
  distance: number
  storeAvatar: string
  storeId: number
  storeName: string
  time: string
}

interface GoodsData {
  descDatail: string
  goodsImgs: Array<GoodsImgs>
  goodsTags: Array<GoodsTags>
  introduce: string
  name: string
  pageView: number
  id: number
  remark: string
  salesPrice: string
  love: number
  sales: string
  status: string
}

export default function CategoryDetail() {
  const location = useLocation()
  const navigate = useNavigate()
  let [userId, setUserId] = useState('')
  let [goodsId, setGoodsId] = useState<number>()
  let [storeId, setStoreId] = useState<number>()
  const [storeData, setStoreData] = useState<StoreData>()
  const [goodsData, setGoodsData] = useState<GoodsData>()
  const [status, setStatus] = useState<'0' | '1' | ''>('')

  useEffect(() => {
    const id = localStorage.getItem('userId')
    const curState = location.state as {
      id: number
      storeId: number
    }
    goodsId = curState.id
    storeId = curState.storeId
    setGoodsId(curState.id)
    setStoreId(curState.storeId)
    if (id) {
      userId = id
      setUserId(id)
    } else {
      navigate('/login')
    }
    getGoodsDate()
    getStoreData()
    delCollect()
  }, [])

  // 获取商品信息
  async function getGoodsDate() {
    Toast.show({
      content: '加载中...',
      maskClickable: false,
      duration: 0,
      icon: <Loading />
    })
    const data = await http('get', '/mty/goods/details', {
      accountId: userId,
      storeId: storeId,
      goodsId: goodsId
    })
    Toast.clear()
    if (data) {
      const res = data.data as DetailGoodsDataType
      setGoodsData({
        descDatail: res.descDatail,
        goodsImgs: res.goodsImgs,
        goodsTags: res.goodsTags,
        introduce: res.introduce,
        name: res.name,
        pageView: res.pageView,
        id: res.id,
        remark: res.remark,
        salesPrice: res.salesPrice,
        love: res.love,
        sales: res.sales,
        status: res.store.status
      })
    }
  }
  // 获取店家信息
  async function getStoreData() {
    const data = await http('get', '/mty/store/headMap', {
      accountId: userId,
      storeId: storeId
    })
    if (data) {
      const res = data.data as DetailStoreType
      setStoreData({
        area: res.area,
        distance: res.distance,
        storeAvatar: res.storeAvatar,
        storeId: res.storeId,
        storeName: res.storeName,
        time: res.time
      })
    }
  }

  // 收藏
  async function collect() {
    if (status !== '') {
      Toast.show({
        content: '加载中...',
        maskClickable: false,
        duration: 0,
        icon: <Loading />
      })
    }
    const data = await http('post', '/mty/collect/add', {
      accountId: userId,
      goodsId,
      storeId
    })
    Toast.clear()

    if (data && data.code === 1) {
      if (status !== '') {
        Toast.show({
          content: '收藏成功，请前往个人中心查看',
          duration: 2000
        })
        setStatus('1')
      }
    }
  }

  async function delCollect() {
    if (status !== '') {
      Toast.show({
        content: '加载中...',
        maskClickable: false,
        duration: 0,
        icon: <Loading />
      })
    }
    const data = await http('post', '/mty/collect/del', {
      accountId: userId,
      goodsId,
      storeId
    })
    Toast.clear()

    if (data && data.code === 1) {
      if (status === '') {
        collect()
        setStatus('1')
      } else {
        Toast.show({
          content: '取消收藏成功',
          duration: 2000
        })
        setStatus('0')
      }
    } else {
      setStatus('0')
    }
  }

  function showImg(i: number) {
    const images: Array<string> = []
    goodsData?.goodsImgs.forEach((item) => {
      images.push(item.img)
    })
    ImageViewer.Multi.show({ images: images, defaultIndex: i })
  }

  return (
    <div style={{ paddingBottom: '190px' }}>
      {/* 顶部导航 */}
      <div className={style['detail-nav']}>
        <div
          className={style['back']}
          onClick={() => {
            navigate(-1)
          }}
        >
          <img src="/static/arrow/icon-back-fff.png" alt="" />
        </div>
        <div className={style['right-icon']}>
          <img src="/static/use/icon-btn-more-fff.png" alt="" />
        </div>
      </div>

      <div className={style['goods-info']}>
        {/* 轮播图 */}
        {goodsData && goodsData?.goodsImgs.length > 0 && (
          <Swiper indicator={() => null}>
            {goodsData?.goodsImgs.map((img, index) => (
              <Swiper.Item key={img.id} onClick={() => showImg(index)}>
                <div className={style['swiper']}>
                  <img src={img.img} alt="" />
                </div>
              </Swiper.Item>
            ))}
          </Swiper>
        )}
        {/* 标题 */}
        <div className={style['title']}>{goodsData?.name}</div>
        {/* 标签 */}
        <div className={style['tags']}>
          {goodsData?.goodsTags.map((tag) => (
            <div className={style['tag-item']} key={tag.id}>
              {tag.tagName}
            </div>
          ))}
        </div>
        {/* 收藏人数 */}
        <div className={style['collection']}>
          <div className={style['stars']}>
            <div className={style['star-item']}>
              <img src="/static/use/icon-star-24-00a.png" alt="" />
            </div>
            <div className={style['star-item']}>
              <img src="/static/use/icon-star-24-00a.png" alt="" />
            </div>
            <div className={style['star-item']}>
              <img src="/static/use/icon-star-24-00a.png" alt="" />
            </div>
            <div className={style['star-item']}>
              <img src="/static/use/icon-star-24-00a.png" alt="" />
            </div>
            <div className={style['star-item']}>
              <img src="/static/use/icon-star-24-00a.png" alt="" />
            </div>
          </div>
          <div className="collect-num">{goodsData?.love}人收藏</div>
        </div>

        {/* 特惠价格 */}
        <div className={style['sales-price']}>
          <div className={style['price']}>
            <span className={style['text']}>特惠价格</span>
            <span className={style['icon']}>￥</span>
            <span className={style['num']}>{goodsData?.salesPrice}</span>
          </div>
          <div className={style['sale-num']}>销量{goodsData?.sales}</div>
        </div>
      </div>

      {/* 商品介绍 */}
      <div className={style['comment']}>
        <div className={style['content']}>
          <div className={style['comment-title']}>商品介绍</div>
          <div className={style['comment-content']}>
            {goodsData?.introduce.split('\n').map((c, index) => (
              <p key={index}>{c}</p>
            ))}
          </div>
        </div>
        <div className={style['detail']}>
          <div className={style['detail-title']}>图文详情</div>
          {goodsData?.descDatail && <div className={style['detail-content']} dangerouslySetInnerHTML={{ __html: goodsData.descDatail }}></div>}
        </div>
      </div>
      {/* 购买须知 */}
      <div className={style['notice']}>
        <div className={style['notice-title']}>
          <div>预定须知</div>
          <div className={style['unsubscribe']}>退订规则</div>
        </div>

        <div className={style['notice-content']}>
          <div className={style['notice-item']}>
            <div className={style['notice-tile']}>预约时间</div>
            <div className={style['notice-text']}>至少提前一天</div>
          </div>
          <div className={style['notice-item']}>
            <div className={style['notice-tile']}>退款方式</div>
            <div className={style['notice-text']}>核销前三天免费退订</div>
          </div>
          <div className={style['notice-item']}>
            <div className={style['notice-tile']}>使用方式</div>
            <div className={style['notice-text']}>到店出示订单二维码</div>
          </div>
          <div className={style['notice-item']}>
            <div className={style['notice-tile']}>温馨提示</div>
            <div className={style['notice-text']}>
              <div className={style['text-item']}>·下单后掌柜将迅速审核订单，请耐心等待，通过后平台将以短信或者推送信息告知您；</div>

              <div className={style['text-item']}>·如有特殊要求，请预定时添加备注或提前联系掌柜后再预定；</div>
              <div className={style['text-item']}>·推定详情可详阅退订规则；</div>
              <div className={style['text-item']}>·预定时请正确选择住宿时间、住宿人数、房价数量；</div>
              <div className={style['text-item']}>·节假日出游记得提前预约哦！</div>
            </div>
          </div>
        </div>
      </div>
      {/* 顶部导航和用户信息 */}
      <div className={style['bottom-nav']}>
        <div className={style['store-info']}>
          <div className={style['head']}>
            <img src={storeData?.storeAvatar} alt="" />
          </div>
          <div className={style['store-detail']}>
            <div className={style['store-title']}>{storeData?.storeName}</div>
            <div className={style['store-content']}>
              <div className={style['address']}>
                <div className={style['address-icon']}>
                  <img src="/static/use/icon-addres-9e9.png" alt="" />
                </div>
                <div>{storeData?.area}</div>
              </div>
              <div className={style['distance']}>距您{storeData?.distance}km</div>
              <div>车程{storeData?.time}分钟</div>
            </div>
          </div>
          <div
            className={style['enter-store']}
            onClick={() => {
              navigate('/store?storeid=' + storeId, {
                state: {
                  storeId,
                  goodsId
                }
              })
            }}
          >
            进店
          </div>
        </div>
        <div className={style['nav']}>
          <div className={style['bottom-nav-item']}>
            <div className={style['nav-icon']}>
              <img src="/static/share/icon-share-505.png" alt="" />
            </div>
            <div>分享</div>
          </div>
          <div className={style['bottom-nav-item']}>
            <div className={style['nav-icon2']}>
              <img src="/static/use/icon-tel-64-505.png" alt="" />
            </div>
            <div>客服</div>
          </div>
          <div className={style['bottom-nav-item']}>
            {status === '0' && (
              <>
                <div className={style['nav-icon3']} onClick={collect}>
                  <img src="/static/share/icon-star-505.png" alt="" />
                </div>
                <div>收藏</div>
              </>
            )}
            {status === '1' && (
              <>
                <div className={style['nav-icon5']} onClick={delCollect}>
                  <img src="/static/use/icon-star-fba.png" alt="" />
                </div>
                <div className={style['collect-status']}>已收藏</div>
              </>
            )}
          </div>
          <div className={style['pay-btn']}>
            <span>立即购买</span>
          </div>
        </div>
      </div>
    </div>
  )
}
